package cn.liccshop.core.service.shopGoods.controller;


import cn.liccshop.core.entity.ShopCategory;
import cn.liccshop.core.entity.ShopGoods;
import cn.liccshop.core.entity.ShopGoodsAttr;
import cn.liccshop.core.entity.ShopPhoto;
import cn.liccshop.core.service.shopCategory.service.IShopCategoryService;
import cn.liccshop.core.service.shopGoods.service.IShopGoodsService;
import cn.liccshop.core.service.shopGoodsAttr.service.IShopGoodsAttrService;
import cn.liccshop.core.service.shopPhoto.service.IShopPhotoService;
import cn.liccshop.core.utils.ObjectToOtherUtils;
import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.entity.Result;
import cn.liccshop.sys.entity.UserElement;
import cn.liccshop.sys.exception.MySystemException;
import cn.liccshop.sys.utils.MapToObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.liccshop.sys.base.MyActionController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description 商品表 前端控制器
 *
 * @author LiCC
 * @since 2019-04-08
 */
@RestController
@RequestMapping("/shopGoods")
public class ShopGoodsController extends MyActionController<ShopGoods> {

    @Autowired
    private IShopGoodsService liShopGoodsService;
    @Autowired
    private IShopPhotoService photoService;
    @Autowired
    private IShopGoodsAttrService attrService;
    @Autowired
    private IShopCategoryService categoryService;

    @Override
    protected IService<ShopGoods> getLiService(){
        return liShopGoodsService;
    }

    /**
     * 管理员添加商品信息
     * @param params
     * @return
     */
    @RequestMapping(value = "/addInfo")
    public Result saveGoodsInfo(@RequestBody Map<String, Object> params) throws MySystemException {
        String userId = getUserInfoByToken().getUserId();
        ShopGoods shopGoods = liShopGoodsService.addShopGoods(params, userId);
        return new Result().setCode(Constants.OK).setData(shopGoods).setMessage("添加成功");
    }
    @RequestMapping(value = "/updateAllInfo")
    public Result updateGoodsAllInfo(@RequestBody Map<String, Object> params) throws MySystemException {
        ShopGoods shopGoods = liShopGoodsService.updateGoodsAllInfo(params);
        return new Result().setCode(Constants.OK).setData(shopGoods).setMessage("更新成功");
    }

    /**
     * 通过商品状态获取商品信息
     * @param map
     * @return
     * @throws MySystemException
     */
    @RequestMapping("listByPage")
    public Result list(@RequestParam("page") Integer page, @RequestParam("size") Integer size, @RequestBody Map<String, Object> map) throws MySystemException {
        ShopGoods shopGoods = MapToObjectUtil.mapToEntity((Map<String, Object>) map.get("shopGoods"), ShopGoods.class);
        String goodsSn = ObjectToOtherUtils.toString(map.get("goodsSn"));
        String goodsName = ObjectToOtherUtils.toString(map.get("goodsName"));
        Integer warnNumber = ObjectToOtherUtils.toInteger(map.get("warnNumber"));
        String startTime = ObjectToOtherUtils.toString(map.get("startTime"));
        String endTime = ObjectToOtherUtils.toString(map.get("endTime"));
        List<Integer> status = MapToObjectUtil.mapToList((JSONArray) map.get("status"), Integer.class);
        Wrapper<ShopGoods> wrapper = new QueryWrapper<>(shopGoods).in("review_status", status);
        if (StringUtils.isNotBlank(goodsSn)){
            ((QueryWrapper<ShopGoods>) wrapper).like("goods_sn", goodsSn);
        }
        if (StringUtils.isNotBlank(goodsName)){
            ((QueryWrapper<ShopGoods>) wrapper).like("goods_name", goodsName);
        }
        if (warnNumber!=null){
            if (warnNumber==1||warnNumber==2){
                ((QueryWrapper<ShopGoods>) wrapper).like("warn_number", warnNumber);
            } else {
                ((QueryWrapper<ShopGoods>) wrapper).eq("goods_number", 0);
            }
        }
        if (StringUtils.isNotBlank(startTime)){
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            ((QueryWrapper<ShopGoods>) wrapper).between("create_date", LocalDateTime.parse(startTime,df),LocalDateTime.parse(endTime,df));
        }
        IPage<ShopGoods> iPage = new Page<>(page, size);
        this.theService().page(iPage, wrapper);
        return new Result().setCode(Constants.OK).setData(iPage);
    }

    /**
     * 新品推荐列表
     * @param map
     * @return
     * @throws MySystemException
     */
    @RequestMapping("newGoodsListByPage")
    public Result newListRecommend(@RequestParam("page") Integer page, @RequestParam("size") Integer size, @RequestBody Map<String, Object> map) throws MySystemException {
        ShopGoods shopGoods = MapToObjectUtil.mapToEntity((Map<String, Object>) map.get("shopGoods"), ShopGoods.class);
        Wrapper<ShopGoods> wrapper = new QueryWrapper<>(new ShopGoods().setReviewStatus(Constants.GOODS_STATUS_10));
        if (shopGoods.getReviewStatus()!=null){
//            ((QueryWrapper<ShopGoods>) wrapper).eq("is_new_goods",shopGoods.getNewGoods()).or().eq("review_status",shopGoods.getReviewStatus()).orderByDesc("create_date");
            ((QueryWrapper<ShopGoods>) wrapper).orderByDesc("create_date");
        } else {
            ((QueryWrapper<ShopGoods>) wrapper).eq("is_new_goods",shopGoods.getNewGoods()).orderByDesc("create_date");
        }
        IPage<ShopGoods> iPage = new Page<>(page, size);
        this.theService().page(iPage, wrapper);
        return new Result().setCode(Constants.OK).setData(iPage);
    }

    /**
     * 热销推荐列表
     * @param map
     * @return
     * @throws MySystemException
     */
    @RequestMapping("hotGoodsListByPage")
    public Result hotListRecommend(@RequestParam("page") Integer page, @RequestParam("size") Integer size, @RequestBody Map<String, Object> map) throws MySystemException {
        ShopGoods shopGoods = MapToObjectUtil.mapToEntity((Map<String, Object>) map.get("shopGoods"), ShopGoods.class);
        Map<String, Object> data = liShopGoodsService.getHotGoodsInfo(page, size, shopGoods);
        return new Result().setCode(Constants.OK).setData(data);
    }

    /**
     * 管理员删除商品信息
     * @param shopGoods
     * @return
     */
    @RequestMapping(value = "/deleteById")
    public Result deleteGoodsById(@RequestBody ShopGoods shopGoods) throws MySystemException {
        if (StringUtils.isBlank(shopGoods.getId())){
            /** id为空，删除失败 **/
            new Result().setCode(Constants.SERVICE_FAIL).setData(shopGoods).setMessage("删除失败");
        }
        liShopGoodsService.deleteGoodsById(shopGoods.getId());
        return new Result().setCode(Constants.OK).setData(shopGoods).setMessage("删除成功");
    }

    @RequestMapping(value = "/allInfoById")
    public Result getAllInfoById(@RequestBody Map<String, Object> map) throws MySystemException {
        /** 获取商品所有信息 **/
        String goodsId = ObjectToOtherUtils.toString(map.get("goodsId"));
        String catId = ObjectToOtherUtils.toString(map.get("catId"));
        Map<String, JSONObject> data = new HashMap<>();
        /** 获取商品基本信息 **/
//        ShopGoods goods = liShopGoodsService.getOne(new QueryWrapper<>(new ShopGoods().setId(goodsId)));
        ShopGoods goods = liShopGoodsService.getById(goodsId);
        data.put("goods", JSON.parseObject(JSON.toJSONString(goods)));
        /** 获取图片信息 **/
        Map<String, List<ShopPhoto>> photoInfos = new HashMap<>();
        List<ShopPhoto> imgThumb = photoService.list(new QueryWrapper<>(new ShopPhoto().setGoodsId(goodsId).setType(1)).orderByAsc("photo_sort"));
        List<ShopPhoto> imgList = photoService.list(new QueryWrapper<>(new ShopPhoto().setGoodsId(goodsId).setType(2)).orderByAsc("photo_sort"));
        photoInfos.put("imgThumb", imgThumb);
        photoInfos.put("imgList", imgList);
        data.put("photoInfos", JSON.parseObject(JSON.toJSONString(photoInfos)));
        /** 分类属性值 **/
        List<Map<String, List<ShopGoodsAttr>>> goodsAttr = attrService.getShopGoodsAttrByGoodsId(goodsId, catId);
        Map<String, List<Map<String, List<ShopGoodsAttr>>>> goodsAttrMap = new HashMap<>();
        goodsAttrMap.put("attributes", goodsAttr);
        data.put("attributes", JSON.parseObject(JSON.toJSONString(goodsAttrMap)));
        /**获取分类属性**/
        Map<String, List<ShopCategory>> categorysMap = new HashMap<>();
        List<ShopCategory> categories = categoryService.shopCategoryInfos(new ShopCategory().setShowInNav((byte) 1).setDisplay((byte) 1));
        categorysMap.put("categorys", categories);
        data.put("initCategorys", JSON.parseObject(JSON.toJSONString(categorysMap)));
        return new Result().setCode(Constants.OK).setData(data).setMessage("获取信息成功");
    }

    /**
     * 前端获取新品和热销商品
     * @return
     */
    @RequestMapping(value = "goodsOfHome")
    public Result getGoodsOfHome(){
        Map<String, Object> data = liShopGoodsService.getGoodsOfHome();
        return new Result().setCode(Constants.OK).setData(data).setMessage("获取信息成功");
    }

    /**
     * 前台获取商品详细信息
     * @return
     */
    @RequestMapping(value = "goodsInfoByIdPro")
    public Result getGoodsInfoByIdPro(@RequestBody Map<String, Object> map) throws MySystemException {
        String goodsId = ObjectToOtherUtils.toString(map.get("goodsId"));
        String catId = ObjectToOtherUtils.toString(map.get("catId"));
        if (StringUtils.isBlank(goodsId)||StringUtils.isBlank(catId)){
            /** 参数异常 **/
            throw new MySystemException("参数异常", Constants.INVALID_PARM);
        }
        /** 获取用户Id **/
        UserElement userElement = getUserInfoByToken();
        String userId = userElement==null?null:userElement.getUserId();
        Map<String, Object> data = liShopGoodsService.getGoodsInfoByIdPro(goodsId, catId, userId);
        return new Result().setCode(Constants.OK).setData(data).setMessage("获取成功");
    }

    /**
     * 前台通过分类ID获取商品信息
     * @param map
     * @return
     */
    @RequestMapping(value = "/goodsByCatIdPro")
    public Result getGoodsInfosByCatIdPro(@RequestBody Map<String, Object> map) throws MySystemException {
        String catId = ObjectToOtherUtils.toString(map.get("catId"));
        Integer pagesize = ObjectToOtherUtils.toInteger(map.get("pagesize"));
        Integer currentPage = ObjectToOtherUtils.toInteger(map.get("currentPage"));
        if (StringUtils.isBlank(catId) || pagesize == null || currentPage == null){
            throw new MySystemException("参数异常",Constants.INVALID_PARM);
        }
        Map<String, Object> data = liShopGoodsService.getGoodsInfosByCatIdPro(catId, pagesize, currentPage);
        return new Result().setCode(Constants.OK).setData(data).setMessage("信息获取成功");
    }
    /**
     * 前台通过搜索获取商品信息
     * @param map
     * @return
     */
    @RequestMapping(value = "/filterGoodsByName")
    public Result filterGoodsByNamePro(@RequestParam("page") Integer page, @RequestParam("size") Integer size, @RequestBody Map<String, Object> map) throws MySystemException {
        String filterName = ObjectToOtherUtils.toString(map.get("filterName"));
        if (StringUtils.isBlank(filterName)){
            throw new MySystemException("参数异常",Constants.INVALID_PARM);
        }
        Map<String, Object> data = liShopGoodsService.filterGoodsByNamePro(filterName, page, size);
        return new Result().setCode(Constants.OK).setData(data).setMessage("信息获取成功");
    }

}

